package com.opener.common.code.assistant.gen;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;

abstract class Generator {
    private Ctx ctx;
    private Ctx.MvcClass mvcClass;
    public Generator(Ctx ctx, Ctx.MvcClass mvcClass){
        this.ctx = ctx;
        this.mvcClass = mvcClass;
    }

    public Ctx getCtx() {
        return ctx;
    }

    public void setCtx(Ctx ctx) {
        this.ctx = ctx;
    }

    public Ctx.MvcClass getMvcClass() {
        return mvcClass;
    }

    public void setMvcClass(Ctx.MvcClass mvcClass) {
        this.mvcClass = mvcClass;
    }

    abstract String createJavaString();
    public String createClassDescString(){
        String s  =
                "/**\n" +
                " * @author baboy\n" +
                " */\n";
        return s;
    }
    public void gen(boolean createFile){
        Ctx.MvcClass cls = getMvcClass();
        File f = cls.getClassFile();
        File d = f.getParentFile();
        if ( !d.exists() ){
            d.mkdirs();
        }
        String c = createJavaString();
        if (!createFile){
            System.out.println(c);
            return;
        }
        try {
            FileOutputStream fos = new FileOutputStream(f);
            fos.write(c.getBytes(Charset.forName("UTF-8")));
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
